package cn.org.july.weixin.service.accesstoken;

import cn.org.july.weixin.common.bean.AccessTokenBean;
import cn.org.july.weixin.common.exception.ErrorCode;
import cn.org.july.weixin.common.exception.IStatus;
import cn.org.july.weixin.common.utils.HttpClientUtils;
import cn.org.july.weixin.service.config.WxConfig;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;

/**
 * 请求AccessTokenService对象
 *
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-08-30 10:44
 * @Description:
 */
@Slf4j
@Service
public class AccessTokenService {

    private final byte[] lock = new byte[0];

    @Resource
    private WxConfig config;

    private AccessTokenBean tokenBean;
    private static final String URL = "https://api.weixin.qq.com/cgi-bin/token";


    private IStatus refreshAccessToken(String appId, String appSecret) {
        HashMap<String, String> tokenBeanRequest = AccessTokenBean.requestOf(appId, appSecret);
        synchronized (lock) {
            String s = null;
            try {
                s = HttpClientUtils.get(URL, tokenBeanRequest);
            } catch (IOException e) {
                log.error("refreshAccessToken is error", e);
            }
            JSONObject jsonObject = JSONObject.parseObject(s);
            String accessToken = jsonObject.getString("access_token");
            String expiresIn = jsonObject.getString("expires_in");
            if (StringUtils.isEmpty(accessToken)) {
                int errCode = jsonObject.getInteger("errcode");
                return ErrorCode.getStatus(errCode);
            }
            tokenBean = AccessTokenBean.responseOf(accessToken, expiresIn);
        }
        return ErrorCode.SUCCESS;
    }

    public String getAccessToken() {
        if (null == tokenBean || tokenBean.isExpired()) {
            IStatus s = refreshAccessToken(config.getAppId(), config.getAppSecret());
            if (ErrorCode.SUCCESS != s) {
                return s.getMessage();
            }
        }
        return tokenBean.getAccessToken();
    }

    /**
     * 获取追加accessToken后的URL
     *
     * @param url 原始URL
     * @return 替换后URL
     */
    public String accessTokenUrl(String url) {
        return url.replace("ACCESS_TOKEN", this.getAccessToken());
    }
}
